package com.bookstore.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bookstore.entity.dto.BookDTO;
import com.bookstore.entity.po.BookPO;
import com.bookstore.entity.pojo.R;
import com.bookstore.entity.vo.BookVO;
import com.bookstore.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("book")
@CrossOrigin
public class BookController {

    @Autowired
    BookService bookService;
    @GetMapping
    public R getAllBooks(Integer start,Integer end) {
        QueryWrapper<BookPO> queryWrapper = new QueryWrapper<>();
        List<BookPO> list = bookService.list();
        List<BookPO> collect = list.stream().filter(v -> v.getStatus().equals(0)).collect(Collectors.toList());
        List<BookPO> bookPOS = collect.subList(start >= collect.size()?collect.size():start , end > collect.size()? collect.size() :end);
        return R.success(bookPOS);
    }

    @GetMapping("selectOne")
    public R selectOneById(Integer id) {
        BookPO byId = bookService.getById(id);
        return byId != null ? R.success(byId) : R.error();
    }
    @PostMapping("search")
    public R search (@RequestBody BookDTO bookDTO) {
        QueryWrapper<BookPO> qw = new QueryWrapper<>();
        if (bookDTO.getBookClass() != 0)
        qw.eq("class_id",bookDTO.getBookClass());
        qw.eq("status",0);
        qw.like("book_name",bookDTO.getBookName());

        List<BookPO> list = bookService.list(qw);
        List<BookVO> list1 = new ArrayList<>();
        for (BookPO bookPO : list) {
            list1.add(new BookVO(bookPO.getId(),bookPO.getBookName()));
        }
        return R.success(list1);
    }
    @PostMapping("find")
    public R find (@RequestBody BookDTO bookDTO) {
        QueryWrapper<BookPO> qw = new QueryWrapper<>();
        if (bookDTO.getBookClass() != 0)
         qw.eq("class_id",bookDTO.getBookClass());
        if (bookDTO.getBookName() != null && !bookDTO.getBookName().equals("")) {
        qw.like("book_name",bookDTO.getBookName());
        }

        List<BookPO> list = bookService.list(qw);
        return R.success(list);
    }
}
